package com.ebo.apicloud;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;

import com.alipay.sdk.app.PayTask;
import com.ebo.agora.openvcall.AGApplication;
import com.ebo.agora.openvcall.model.ConstantApp;
import com.ebo.agora.openvcall.ui.MainActivity;
import com.ebo.download.download2.DownloadListActivity;
import com.ebo.download.download2.DownloadTask;
import com.ebo.download.download2.DownloadTaskManager;
import com.ebo.pay.alipay.PayResult;
import com.ebo.supervideoplayer.MyTestActivity;
import com.ebo.zxing.QrCodeActivity;
import com.uzmap.pkg.openapi.ExternalActivity;
import com.uzmap.pkg.openapi.Html5EventListener;
import com.uzmap.pkg.openapi.WebViewProvider;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.Map;

import utils.IToast;
import utils.Lg;

import static com.ebo.agora.openvcall.IBaseActivity.removeALLActivity;
import static com.ebo.agora.openvcall.IBaseActivity.show_Toast;


/**
 * Created by admin on 2017/4/12.aaaaaaaaaa
 */

public class H5Activity extends ExternalActivity {
    public static final String SDCARD = Environment.getExternalStorageDirectory().getPath() + "/ebo/study/download/";
    public static final String KEY_OPEN_H5 = "open_h5";
    public static final String EVENT_ZXING_REQ = "zxing_req";//请求扫码
    public static final String EVENT_ZXING_RESULT = "zxing_result";//扫码返回值

    public static final int ACTIVITY_REQ_ZXING = 1;//扫码返回值
    public static final int ACTIVITY_RESULTCODE_ZXING_SUCCESS = 1;//扫码返回值-成功
    public static final int ACTIVITY_RESULTCODE_ZXING_NONE = 2;//扫码返回值-空值


    public static final String EVENT_PLAY_VIDEO = "play_video";//请求播放视频
    public static final String EVENT_DOWNLOAD = "download";//请求下载

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindSomething();
        checkSelfPermissions();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getIntent().getBooleanExtra(KEY_OPEN_H5, false)) {
            mhandle.sendEmptyMessageDelayed(1, 1500);
        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        switch(keyCode){
//            case KeyEvent.KEYCODE_BACK:
//                startActivityForResult(new Intent().setClass(H5Activity.this, QrCodeActivity.class), ACTIVITY_REQ_ZXING);
//                return  true;
//        }
//        return false;
//    }

    private void bindSomething() {
        //下载
        addHtml5EventListener(new Html5EventListener(EVENT_DOWNLOAD) {
            @Override
            public void onReceive(WebViewProvider provider, Object extra) {
                Lg.d("EVENT_DOWNLOAD extra="+extra);
                try {
                    JSONObject jb = new JSONObject(extra.toString());
                    String url = jb.getString("url");
                    String filename = jb.getString("filename");

                    DownloadTask downloadTask = new DownloadTask(
                            url, SDCARD, filename, filename, null);
                    DownloadTaskManager.getInstance(H5Activity.this).startDownload(downloadTask);

                    Intent i = new Intent(H5Activity.this, DownloadListActivity.class);
                    i.putExtra(DownloadListActivity.DOWNLOADED, false);
                    startActivity(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Lg.d("extra=" + extra);
            }
        });


        //播放视频
        addHtml5EventListener(new Html5EventListener(EVENT_PLAY_VIDEO) {
            @Override
            public void onReceive(WebViewProvider provider, Object extra) {
                try {
                    JSONObject jb = new JSONObject(extra.toString());
                    String url = jb.getString("url");
                    Intent appIntent = new Intent();
                    appIntent.setClass(H5Activity.this, MyTestActivity.class);
                    appIntent.putExtra("url", url);
                    startActivity(appIntent);


//                    Intent i = new Intent().setClass(H5Activity.this, MyTestActivity.class);
//                    i.putExtra("url", url);
//                    startActivity(i);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Lg.d("extra=" + extra);

            }
        });


        //扫码
        addHtml5EventListener(new Html5EventListener(EVENT_ZXING_REQ) {
            @Override
            public void onReceive(WebViewProvider provider, Object extra) {
                startActivityForResult(new Intent().setClass(H5Activity.this, QrCodeActivity.class), ACTIVITY_REQ_ZXING);
            }
        });

        //退出
        addHtml5EventListener(new Html5EventListener("myEvent") {
            @Override
            public void onReceive(WebViewProvider provider, Object extra) {
                exit();
            }
        });
        //视频
        addHtml5EventListener(new Html5EventListener("videoMsg") {
            @Override
            public void onReceive(WebViewProvider provider, Object extra) {
                try {
                    JSONObject jb = new JSONObject(extra.toString());
                    channel_name = jb.getString("room_name");
                    uid = jb.getString("user_id");
                    sid = jb.getString("sid");
//                    html_url = jb.getString("html_url");
                    Intent i = new Intent().setClass(H5Activity.this, MainActivity.class);
                    i.putExtra("channel_name", channel_name);
                    i.putExtra("uid", uid);
                    startActivity(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Lg.d("extra=" + extra);
            }
        });
        //支付宝付款
        addHtml5EventListener(new Html5EventListener("submitOrder") {
            @Override
            public void onReceive(WebViewProvider provider, Object extra) {
                try {
                    JSONObject jb = new JSONObject(extra.toString());
                    ali_price = (float) jb.getDouble("price");
                    alipay_info = jb.getString("alipay_info");
//                    ali_cid = jb.getString("cid");
                    Lg.d("ali_price=" + ali_price + ",alipay_info=" + alipay_info);
//                    sendToH5();
                    payAli(null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        Lg.d("onActivityResult 11111111111111111 data="+data);
        switch (requestCode) {
            case ACTIVITY_REQ_ZXING:
                onActivityResultZxing(resultCode, data);
                break;
        }
    }

    private void onActivityResultZxing(int resultCode, Intent data) {
        String zxing_url = null;
        switch (resultCode) {
            case ACTIVITY_RESULTCODE_ZXING_NONE:
                break;
            case ACTIVITY_RESULTCODE_ZXING_SUCCESS:
                zxing_url = data.getStringExtra("zxing_url");
                break;
        }
        Lg.d("zxing_url=" + zxing_url);
        JSONObject extra = new JSONObject();
        try {
            extra.put("zxing_url", zxing_url);
        } catch (Exception e) {
        }
        sendEventToHtml5(EVENT_ZXING_RESULT, extra);
    }

    String channel_name, uid;
    float ali_price;
    String alipay_info;
    public static String sid;

    //退出方法
    private long time = 0;

    private void exit() {
        //如果在两秒大于2秒
        if (System.currentTimeMillis() - time > 2000) {
            //获得当前的时间
            time = System.currentTimeMillis();
            show_Toast("再点击一次退出应用程序");
        } else {
            //点击在两秒以内
            removeALLActivity();//执行移除所以Activity方法
            System.exit(0);
        }
    }


    //alipay===============================================================================
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    sendToH5_Alipay(resultStatus.equals("9000") ? 0 : 1);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //付费成功
                        String out_trade_no = "";// payResult.getOut_trade_no();
                        float total_amount = 0;// payResult.getTotal_amount();
                        try {
                            JSONObject j = new JSONObject(resultInfo);
                            Lg.d("j=" + j.toString());
                            JSONObject j2 = j.getJSONObject("alipay_trade_app_pay_response");
                            out_trade_no = j2.getString("out_trade_no");
                            total_amount = Float.valueOf(j2.getString("total_amount"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Lg.d("out_trade_no=" + out_trade_no + ",total_amount=" + total_amount);
//                        Pub.send_CheckOrder(PayActivity.this, out_trade_no, total_amount, new PostCheckOrder());

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        if (TextUtils.equals(resultStatus, "8000")) {
                            IToast.show(H5Activity.this, "正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态");
                        } else if (TextUtils.equals(resultStatus, "4000")) {
                            IToast.show(H5Activity.this, "订单支付失败");
                        } else if (TextUtils.equals(resultStatus, "5000")) {
                            IToast.show(H5Activity.this, "重复请求");
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            IToast.show(H5Activity.this, "用户中途取消");
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                            IToast.show(H5Activity.this, "网络连接出错");
                        } else if (TextUtils.equals(resultStatus, "6004")) {
                            IToast.show(H5Activity.this, "支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态");
                        } else {
                            IToast.show(H5Activity.this, "支付失败，未知原因，请联系运营商");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * 支付宝支付业务
     * 支付宝支付业务
     *
     * @param v
     */
    public void payAli(View v) {

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(H5Activity.this);
                Map<String, String> result = alipay.payV2(alipay_info, true);
                Lg.d("map=" + result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //alipay end===============================================================================
    private void sendToH5_Alipay(int code) {
        JSONObject extra = new JSONObject();
        try {
//            extra.put("cid", ali_cid);
            extra.put("code", code);
        } catch (Exception e) {
        }
        //"fromNative"与assets/widgetml/wind.html页面的apiready中注册的监听相对应
        sendEventToHtml5("alipay_result", extra);
//        Lg.d("111","123456");
    }

    private void sendToH5_Open_H5() {
        JSONObject extra = new JSONObject();
        try {
            extra.put("sid", sid);
//            extra.put("html_url", html_url);
        } catch (Exception e) {
        }
        Lg.d("1111111111111111111111111111111");
        sendEventToHtml5("vi", extra);
    }

    Handler mhandle = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    sendToH5_Open_H5();
                    break;
            }
        }
    };


    private boolean checkSelfPermissions() {
        return checkSelfPermission(Manifest.permission.RECORD_AUDIO, ConstantApp.PERMISSION_REQ_ID_RECORD_AUDIO) &&
                checkSelfPermission(Manifest.permission.CAMERA, ConstantApp.PERMISSION_REQ_ID_CAMERA) &&
                checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, ConstantApp.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE);
    }

    public boolean checkSelfPermission(String permission, int requestCode) {
        Lg.d("checkSelfPermission " + permission + " " + requestCode);
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
//            Lg.d("ffffffff");
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
            return false;
        }
//        Lg.d("ttttttt");
//        if (Manifest.permission.CAMERA.equals(permission)) {
//            ((AGApplication) getApplication()).initWorkerThread();
//        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        Lg.d("onRequestPermissionsResult " + requestCode + " " + Arrays.toString(permissions) + " " + Arrays.toString(grantResults));
        switch (requestCode) {
            case ConstantApp.PERMISSION_REQ_ID_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.CAMERA, ConstantApp.PERMISSION_REQ_ID_CAMERA);
                } else {
                    IToast.show("请手动打开麦克风权限");
                }
                break;
            }
            case ConstantApp.PERMISSION_REQ_ID_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, ConstantApp.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE);
                    ((AGApplication) getApplication()).initWorkerThread();
                } else {
                    IToast.show("请手动打开相机权限");
                }
                break;
            }
            case ConstantApp.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    IToast.show("请手动打开访问SD卡权限");
                }
                break;
            }
        }
    }


}